package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.admin.entity.AdChannel;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.AdChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.admin.dtos.ChannelDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2021-11-22
 */
@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {
    /**
     * 分页查询频道信息
     * @param dto
     * @return
     */
    @Override
    public PageResult<ChannelDto> findByPage(ChannelDto dto) {
//        设置分页,size page
        IPage<AdChannel> ipage = new Page<>(dto.getPage(),dto.getSize());
//        设置查询条件
//        select * from ad_channel where name like '%name%'
//        创建条件包装对象
        QueryWrapper<AdChannel> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(dto.getName())){
            queryWrapper.like("name",dto.getName());
        }
//        进行分页查询
        IPage<AdChannel> channelIPage = page(ipage, queryWrapper);
        if(channelIPage == null || CollectionUtils.isEmpty(channelIPage.getRecords())){
//            return null;
//            throw new RuntimeException("没有查询到结果");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        做对象转换 ad转dto
        List<ChannelDto> channelDtoList = BeanHelper.copyWithCollection(channelIPage.getRecords(), ChannelDto.class);
//        处理结果构造pageResult
        return new PageResult<>(
                dto.getPage(),
                dto.getSize(),
                channelIPage.getTotal(),
                channelDtoList);
    }
}
